export const dragging = {
  bind(el, binding) {
    el.draggable = true
    el.style.cursor = 'move'
    el.style.userSelect = 'none'

    el.ondragstart = function(e) {
      e.dataTransfer.effectAllowed = 'move'
      e.dataTransfer.setData('item', JSON.stringify(binding.value.item))
      el.classList.add('dragging')
    }

    el.ondragend = function(e) {
      el.classList.remove('dragging')
    }

    el.ondragover = function(e) {
      e.preventDefault()
      e.dataTransfer.dropEffect = 'move'
    }

    el.ondrop = function(e) {
      e.preventDefault()
      const sourceItem = JSON.parse(e.dataTransfer.getData('item'))
      const targetItem = binding.value.item

      if (sourceItem && targetItem) {
        // 交换两个课程的时间和位置
        const tempWeekDay = sourceItem.weekDay
        const tempLessonNo = sourceItem.lessonNo

        sourceItem.weekDay = targetItem.weekDay
        sourceItem.lessonNo = targetItem.lessonNo
        targetItem.weekDay = tempWeekDay
        targetItem.lessonNo = tempLessonNo

        // 更新列表数据
        const list = binding.value.list
        const sourceIndex = list.findIndex(item => item.id === sourceItem.id)
        const targetIndex = list.findIndex(item => item.id === targetItem.id)

        if (sourceIndex !== -1 && targetIndex !== -1) {
          list.splice(sourceIndex, 1, sourceItem)
          list.splice(targetIndex, 1, targetItem)
        }
      }
    }
  },
  unbind(el) {
    el.ondragstart = null
    el.ondragend = null
    el.ondragover = null
    el.ondrop = null
  }
}